package com.behelpful.common.data.typehandler;

import com.alibaba.fastjson.JSONObject;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;
import org.apache.ibatis.type.TypeHandler;
import org.springframework.stereotype.Component;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * Json 和字符串转换的类型拦截器
 *
 * @author Alay
 * @date 2021-09-03 15:00
 */
@Component
@MappedJdbcTypes(value = JdbcType.VARCHAR)
@MappedTypes(value = {JSONObject.class})
public class JsonTypeHandler implements TypeHandler<JSONObject> {


    @Override
    public void setParameter(PreparedStatement preparedStatement, int index, JSONObject json, JdbcType jdbcType) throws SQLException {
        if (null == json || json.isEmpty()) {
            preparedStatement.setString(index, null);
            return;
        }
        preparedStatement.setString(index, json.toString());
    }

    @Override
    public JSONObject getResult(ResultSet resultSet, String columnName) throws SQLException {
        String jsonStr = resultSet.getString(columnName);
        if (null == jsonStr) {
            return null;
        }
        JSONObject json = JSONObject.parseObject(jsonStr);
        return json;
    }

    @Override
    public JSONObject getResult(ResultSet resultSet, int columnIndex) throws SQLException {
        String jsonStr = resultSet.getString(columnIndex);
        if (null == jsonStr) {
            return null;
        }
        JSONObject json = JSONObject.parseObject(jsonStr);
        return json;
    }

    @Override
    public JSONObject getResult(CallableStatement callableStatement, int columnIndex) throws SQLException {
        String jsonStr = callableStatement.getString(columnIndex);
        if (null == jsonStr) {
            return null;
        }
        JSONObject json = JSONObject.parseObject(jsonStr);
        return json;
    }
}
